from django import forms
from Login import models
import re


# 更新用户信息表单校验
class update_user_informationModelForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = ["email", "user_name", "user_birthday", "address", "user_age", "phone", "introduce"]

    substrings = ['tmd', 'fuck', '傻逼']  # 存放敏感词

    def clean_email(self):
        # 这里进行邮箱格式的判断
        value = self.cleaned_data.get('email')
        if len(value) < 1:
            raise forms.ValidationError("邮箱长度小于1")
        pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
        if not pattern.match(value):
            raise forms.ValidationError("邮箱格式错误")
        if models.User.objects.filter(email=value).exists():
            raise forms.ValidationError("该邮箱已被注册")
        return value

    def clean_user_name(self):
        value = self.cleaned_data.get('user_name')
        if models.User.objects.filter(user_name=value).exists():
            raise forms.ValidationError("账号已存在")
        return value

    def clean_introduce(self):
        value = self.cleaned_data.get('introduce')
        # 由于用户没有更改简介但程序运行到这里时报错，所以先进行判断
        if not value:
            return value
        if len(value) > 50:
            raise forms.ValidationError("输入不能大于50字")
        for substring in self.substrings:
            if substring in value:
                raise forms.ValidationError(f"请对文章进行修改，不要使用敏感词:{substring}！！！")
        return value


# 修改密码表单校验
class alter_passwordModelForm(forms.ModelForm):
    code = forms.CharField(max_length=32)
    password_verify = forms.CharField(max_length=64)

    class Meta:
        model = models.User
        fields = ["password", "code", "password_verify"]

    def clean_code(self):
        value = self.cleaned_data.get('code')
        if not value:
            raise forms.ValidationError("未输入验证码")
        return value

    def clean_password(self):
        value = self.cleaned_data.get('password')
        if not value:
            raise forms.ValidationError("请输入密码")
        return value

    def clean_password_verify(self):
        value = self.cleaned_data.get('password_verify')
        if not value:
            raise forms.ValidationError("请确认密码")
        return value
